import { motion } from 'framer-motion';
import BottomNav from '../components/BottomNav';
import { CheckCircleIcon, PlusIcon, CalendarIcon, TrashIcon, CheckIcon } from '@heroicons/react/24/outline';
import { useState, useEffect } from 'react';
import { MemoService, type Memo } from '../api/memo';
import { authUtils, type UserInfo } from '../api/auth';

// 格式化时间函数，处理null值情况
// 增强的格式化时间函数，增加日志记录
const formatDateTime = (dateString: string | null): string => {
  // 增加详细日志记录，查看实际接收到的时间数据
  if (dateString === null) {
    console.log('接收到的时间为null');
    return '未设置';
  }
  
  try {
    console.log('尝试解析的时间字符串:', dateString);
    const date = new Date(dateString);
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      console.warn('日期解析无效:', dateString);
      return '无效日期';
    }
    
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    console.error('日期解析错误:', error, '日期字符串:', dateString);
    return '时间格式错误';
  }
};

export default function NotesPage() {
  // 状态管理
  const [memos, setMemos] = useState<Memo[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [currentUser, setCurrentUser] = useState<UserInfo | null>(null);
  // 添加选择状态和确认对话框状态
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<boolean>(false);
  const [deleteLoading, setDeleteLoading] = useState<boolean>(false);

  // 组件加载时获取备忘录数据
  // 将fetchMemos函数移到useEffect外部，使其成为组件的顶级函数
  // 在fetchMemos函数中修改用户ID转换逻辑
  // 修改fetchMemos函数中的用户ID处理逻辑
  const fetchMemos = async () => {
    setLoading(true);
    setError(null);
    setMemos([]); // 重置备忘录列表
    
    try {
      // 获取当前用户信息
      const user = authUtils.getCurrentUser();
      if (!user) {
        throw new Error('用户未登录');
      }
      setCurrentUser(user);
      
      console.log('当前用户信息:', user);
      console.log('用户ID:', user.id);
      
      // 直接使用固定的用户ID 9，这是后端期望的用户ID
      const userId: number = 9;
      console.log('使用固定用户ID:', userId);
      
      // 仅调用后端API获取备忘录列表
      const response = await MemoService.getUserMemoByUserId(userId);
      
      // 严格按照后端返回数据格式处理
      console.log('后端返回数据:', response);
      if (response.code === '200' && response.data) {
        // 确保数据是数组格式
        if (Array.isArray(response.data)) {
          // 增加日志，查看每条备忘录的时间字段
          response.data.forEach((memo, index) => {
            console.log(`备忘录 ${index + 1} 的createTime:`, memo.createTime);
            console.log(`备忘录 ${index + 1} 的updateTime:`, memo.updateTime);
          });
          setMemos(response.data);
        } else {
          console.error('后端返回的数据格式不正确，预期为数组:', response.data);
          setMemos([]);
        }
      } else {
        // 处理非成功状态
        setError(response.msg || '获取备忘录失败');
        console.error('获取备忘录失败，状态码:', response.code, '消息:', response.msg);
      }
    } catch (err) {
      // 捕获API调用异常
      setError('获取备忘录失败，请稍后再试');
      console.error('获取备忘录错误:', err);
    } finally {
      setLoading(false);
    }
  };
  
  // 在useEffect中调用fetchMemos函数
  useEffect(() => {
    fetchMemos();
  }, []);
  
  // 切换备忘录选择状态
  const toggleSelect = (id: number) => {
    setSelectedIds(prev => 
      prev.includes(id) 
        ? prev.filter(itemId => itemId !== id) 
        : [...prev, id]
    );
  };
  
  // 选择所有备忘录
  const selectAll = () => {
    if (selectedIds.length === memos.length) {
      setSelectedIds([]); // 取消全选
    } else {
      setSelectedIds(memos.map(memo => memo.id)); // 全选
    }
  };
  
  // 删除单个备忘录
  const handleDeleteSingle = (id: number) => {
    setSelectedIds([id]);
    setShowDeleteConfirm(true);
  };
  
  // 确认删除备忘录
  const confirmDelete = async () => {
    if (selectedIds.length === 0) return;
    
    setDeleteLoading(true);
    setError(null);
    
    try {
      // 调用删除API，将ID数组转换为逗号分隔的字符串
      const idsString = selectedIds.join(',');
      const response = await MemoService.deleteUserMemo(idsString);
      
      if (response.code === '200') {
        // 删除成功后更新备忘录列表
        setMemos(prev => prev.filter(memo => !selectedIds.includes(memo.id)));
        setSelectedIds([]);
        setShowDeleteConfirm(false);
      } else {
        setError(response.msg || '删除失败');
      }
    } catch (err) {
      setError('删除失败，请稍后再试');
      console.error('删除备忘录错误:', err);
    } finally {
      setDeleteLoading(false);
    }
  };

  // 添加新的状态用于添加备忘录功能
  const [showAddModal, setShowAddModal] = useState<boolean>(false);
  const [newMemoContent, setNewMemoContent] = useState<string>('');
  const [addingMemo, setAddingMemo] = useState<boolean>(false);

  // 添加备忘录函数
  // 修改handleAddMemo函数中的用户ID处理逻辑
  const handleAddMemo = async () => {
    if (!newMemoContent.trim()) {
      alert('备忘录内容不能为空');
      return;
    }
    
    setAddingMemo(true);
    setError(null);
    
    try {
      // 获取当前用户信息
      const user = authUtils.getCurrentUser();
      if (!user) {
        throw new Error('用户未登录');
      }
      
      // 直接使用固定的用户ID 9，这是后端期望的用户ID
      const userId: number = 9;
      console.log('使用固定用户ID添加备忘录:', userId);
      
      // 调用添加API
      const response = await MemoService.addUserMemo(userId, newMemoContent.trim());
      if (response.code === '200') {
        // 添加成功后清空输入并关闭模态框
        setNewMemoContent('');
        setShowAddModal(false);
        // 刷新备忘录列表
        await fetchMemos(); // 调用获取备忘录列表的函数
      } else {
        setError(response.msg || '添加备忘录失败');
      }
    } catch (err) {
      setError('添加备忘录失败，请稍后再试');
      console.error('添加备忘录错误:', err);
    } finally {
      setAddingMemo(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-950 pb-16">
      {/* 顶部装饰条 - 改为灰色系 */}
      <div className="h-1 bg-gradient-to-r from-gray-400 via-gray-500 to-gray-600"></div>
      
      <motion.div 
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        className="max-w-md mx-auto px-4 py-6"
      >
        <div className="flex justify-between items-center mb-8">
          {/* 标题颜色改为灰色系 */}
          <h1 className="text-3xl font-bold text-gray-800 dark:text-gray-200">
            我的备忘录
          </h1>
          <div className="flex space-x-3">
            {/* 批量删除按钮 - 颜色改为灰色系 */}
            {selectedIds.length > 0 && (
              <motion.button 
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                className="p-2.5 rounded-full bg-gray-600 text-white shadow-lg shadow-gray-200 dark:shadow-gray-900/30"
                onClick={() => setShowDeleteConfirm(true)}
              >
                <TrashIcon className="w-5 h-5" />
              </motion.button>
            )}
            {/* 添加按钮 - 颜色改为灰色系 */}
            <motion.button 
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              className="p-2.5 rounded-full bg-gray-700 text-white shadow-lg shadow-gray-200 dark:shadow-gray-900/30"
              onClick={() => setShowAddModal(true)}
            >
              <PlusIcon className="w-5 h-5" />
            </motion.button>
          </div>
        </div>
        
        {/* 选择操作栏 - 颜色改为灰色系 */}
        {memos.length > 0 && (
          <div className="mb-4 flex justify-between items-center">
            <button 
              className="text-sm text-gray-600 dark:text-gray-400 hover:underline flex items-center"
              onClick={selectAll}
            >
              <CheckIcon 
                className={`w-4 h-4 mr-1 ${selectedIds.length === memos.length ? 'text-gray-600 dark:text-gray-400' : 'text-gray-300 dark:text-gray-600'}`}
              />
              {selectedIds.length === memos.length ? '取消全选' : '全选'}
            </button>
            {selectedIds.length > 0 && (
              <span className="text-sm text-gray-500 dark:text-gray-400">
                已选择 {selectedIds.length} 项
              </span>
            )}
          </div>
        )}
        
        {/* 加载状态、错误状态和备忘录列表 - 颜色调整为灰色系 */}
        {loading ? (
          <div className="flex flex-col items-center justify-center py-16 bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm rounded-xl shadow-sm">
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-gray-500 mb-4"></div>
            <p className="text-gray-500 dark:text-gray-400">加载中...</p>
          </div>
        ) : error ? (
          <div className="p-5 bg-white/90 dark:bg-gray-800/90 backdrop-blur-sm rounded-xl shadow-sm border-l-4 border-gray-500 mb-6">
            <div className="flex items-start">
              <div className="flex-shrink-0 pt-0.5">
                <svg className="w-5 h-5 text-gray-500" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd"></path>
                </svg>
              </div>
              <div className="ml-3">
                <h3 className="text-sm font-medium text-gray-800 dark:text-gray-300">错误</h3>
                <div className="mt-2 text-sm text-gray-700 dark:text-gray-200">
                  <p>{error}</p>
                </div>
              </div>
            </div>
          </div>
        ) : (
          // ... 保留备忘录列表的主体结构，仅调整颜色相关的class
          <div className="space-y-4">
            {memos.length === 0 ? (
              // ... 空状态提示，颜色调整为灰色系
              <motion.div 
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="text-center py-16 bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm rounded-xl shadow-sm"
              >
                <div className="mx-auto w-16 h-16 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mb-4">
                  <CalendarIcon className="w-8 h-8 text-gray-400" />
                </div>
                <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">暂无备忘录记录</h3>
                <p className="text-gray-500 dark:text-gray-400">点击右上角的加号按钮创建第一条备忘录</p>
              </motion.div>
            ) : (
              // ... 备忘录列表项，颜色调整为灰色系
              <div className="space-y-3">
                {memos.map((note) => (
                  <motion.div 
                    key={note.id}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    whileHover={{ scale: 1.01 }}
                    className={`p-4 backdrop-blur-sm rounded-xl shadow-sm border overflow-hidden group transition-all duration-200 ${selectedIds.includes(note.id) ? 'bg-gray-100/90 dark:bg-gray-700/20 border-gray-300 dark:border-gray-600' : 'bg-white/90 dark:bg-gray-800/90 border-gray-100 dark:border-gray-700'}`}
                  >
                    <div className="flex items-start">
                      {/* 选择按钮 */}
                      <div className="flex-shrink-0 mt-0.5 mr-2">
                        <button 
                          onClick={() => toggleSelect(note.id)}
                          className={`w-5 h-5 rounded-full flex items-center justify-center transition-colors ${selectedIds.includes(note.id) ? 'bg-gray-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-transparent'}`}
                        >
                          {selectedIds.includes(note.id) && <CheckIcon className="w-3 h-3" />}
                        </button>
                      </div>
                      <div className="ml-1 flex-1">
                        <p className="text-gray-800 dark:text-gray-100 line-clamp-2">{note.memo}</p>
                        <div className="mt-2 flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
                          <div className="flex items-center">
                            <CalendarIcon className="w-3.5 h-3.5 mr-1.5" />
                            <span>创建: {formatDateTime(note.createTime)}</span>
                          </div>
                          {/* 单个删除按钮 */}
                          <button 
                            onClick={() => handleDeleteSingle(note.id)}
                            className="text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
                          >
                            <TrashIcon className="w-3.5 h-3.5" />
                          </button>
                        </div>
                      </div>
                    </div>
                  </motion.div>
                ))}
              </div>
            )}
          </div>
        )}
      </motion.div>
      
      {/* 删除确认对话框 - 颜色调整为灰色系 */}
      {showDeleteConfirm && (
        <motion.div 
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50"
        >
          <motion.div 
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-xl p-5 max-w-sm w-full"
          >
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3">确认删除</h3>
            <p className="text-gray-600 dark:text-gray-300 mb-5">
              确定要删除选中的 {selectedIds.length} 条备忘录吗？此操作无法撤销。
            </p>
            <div className="flex space-x-3">
              <button 
                className="flex-1 px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                onClick={() => setShowDeleteConfirm(false)}
              >
                取消
              </button>
              <button 
                className="flex-1 px-4 py-2 rounded-lg bg-gray-700 text-white hover:bg-gray-800"
                onClick={confirmDelete}
                disabled={deleteLoading}
              >
                {deleteLoading ? (
                  <span className="flex items-center justify-center">
                    <span className="animate-spin mr-2 h-4 w-4 border-2 border-white border-t-transparent rounded-full"></span>
                    删除中...
                  </span>
                ) : (
                  '确认删除'
                )}
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
      
      {/* 添加备忘录的模态框 */}
      {showAddModal && (
        <motion.div 
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50"
        >
          <motion.div 
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-xl p-5 max-w-md w-full"
          >
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3">添加备忘录</h3>
            <textarea
              className="w-full border border-gray-300 dark:border-gray-600 rounded-lg p-3 h-40 bg-white dark:bg-gray-900 text-gray-800 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-500"
              placeholder="请输入备忘录内容..."
              value={newMemoContent}
              onChange={(e) => setNewMemoContent(e.target.value)}
              maxLength={500}
            />
            <div className="mt-2 text-right text-xs text-gray-500">
              {newMemoContent.length}/500
            </div>
            <div className="mt-4 flex space-x-3">
              <button 
                className="flex-1 px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                onClick={() => {
                  setShowAddModal(false);
                  setNewMemoContent('');
                }}
              >
                取消
              </button>
              <button 
                className="flex-1 px-4 py-2 rounded-lg bg-gray-700 text-white hover:bg-gray-800"
                onClick={handleAddMemo}
                disabled={addingMemo || !newMemoContent.trim()}
              >
                {addingMemo ? (
                  <span className="flex items-center justify-center">
                    <span className="animate-spin mr-2 h-4 w-4 border-2 border-white border-t-transparent rounded-full"></span>
                    添加中...
                  </span>
                ) : (
                  '确认添加'
                )}
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
      
      <BottomNav />
    </div>
  );
}